package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.RequestProcessorImp;

import java.util.Date;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.msg.ExceptionResponse;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ModbusUtil;
import net.wimpi.modbus.msg.WriteCoilRequest;
import net.wimpi.modbus.msg.WriteCoilResponse;
import net.wimpi.modbus.procimg.DigitalOut;
import net.wimpi.modbus.procimg.IllegalAddressException;
import net.wimpi.modbus.procimg.SimpleDigitalOut;

public class WriteCoilRequestProcessor extends AbstractRequestProcessor {
	
	private static final Integer INT_1 = new Integer(1);
	private static final Integer INT_0 = new Integer(0);

	@Override
	public ModbusResponse processRequest(ModbusRequest req) {
		
		ModbusResponse res;
		//TODO: chequear limites del protocolo
		int reference = ((WriteCoilRequest)req).getReference();
		DigitalOut value = new SimpleDigitalOut(((WriteCoilRequest) req).getCoil());
		Date date = new Date();
		
		try {
			
			getImage().setDigitalOut(reference, value, date);
			
			if( getDeciveDAO() != null )
				if(value.isSet())
					getDeciveDAO().saveValue( getDevice(), reference ,INT_1 , AddressType.COIL );
				else
					getDeciveDAO().saveValue( getDevice(), reference ,INT_0 , AddressType.COIL );
					
			res = new WriteCoilResponse(reference, getImage().getDigitalIn(reference).isSet());
			
			ModbusUtil.setFunctionCode(res, Modbus.WRITE_COIL);
		}
		catch(IllegalAddressException e){
			res = new ExceptionResponse(req.getFunctionCode(), 2);
		}
		
		ModbusUtil.setMessageData(res,req);
		return res;
		
	}

}
